import { Effect, Reducer } from 'umi';

import { getSubscribeWidgets, savePosition } from '@/services/selfquery';

import { subscribeWidgetsItem } from '../type';

export interface SubscribeModelState {
  subscribeWidgets: Array<subscribeWidgetsItem>
}

export interface SubscribeModelType {
  namespace: 'subscribe';
  state: SubscribeModelState;
  effects: {
    fetchSubscribeWidgets: Effect;
    preservePosition: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const SubscribeModel: SubscribeModelType = {
  namespace: 'subscribe',

  state: {
    subscribeWidgets: []
  },

  effects: {
    // 获取我的订阅列表
    *fetchSubscribeWidgets({ payload }, { call, put }) {
      const response = yield call(getSubscribeWidgets, payload);
      yield put({
        type: 'save',
        payload: { subscribeWidgets: response.payload }
      });
    },

    // 保存订阅列表排版
    *preservePosition({ payload, callback }, { call }) {
      const response = yield call(savePosition, payload);

      if (callback) callback(response);
    },
  },

  reducers: {
    save (state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default SubscribeModel;
